package top.luckyluxcis.util;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.util.ParameterizedTypeImpl;

import java.lang.reflect.Type;

/**
 * @author Zhuang
 * @since 2023/9/25
 */
public class JsonUtil {
    /**
     * 为序列化两次以上泛型提供的工具类
     *
     * @param json                json
     * @param topType             顶部类型
     * @param actualTypeArguments 实际类型参数
     * @return {@link T}
     */
    public static <T> T parseObject(String json, Type topType, Type... actualTypeArguments) {
        Type[] result = new Type[actualTypeArguments.length + 1];
        result[0] = topType;
        System.arraycopy(actualTypeArguments, 0, result, 1, actualTypeArguments.length);

        ParameterizedTypeImpl beforeType = null;
        for (int i = result.length - 1; i > 0; i--) {
            beforeType = new ParameterizedTypeImpl(new Type[]{beforeType == null ? result[i] : beforeType}, null, result[i - 1]);
        }
        return JSONObject.parseObject(json, beforeType);
    }
}
